package com.f.listener;

import com.f.bo.IdStatusBo;
import com.f.client.ProcessClient;
import com.f.constant.Constant;
import com.f.utils.ApplicationContextUtils;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.cfg.TransactionState;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 全局流程执行完成监听器
 *
 * @author liuf
 * @date 2022年12月29日
 */
@Service
public class FlowCompletedListener implements FlowableEventListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(FlowCompletedListener.class);

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        LOGGER.info("FlowCompletedListener onEvent:{}", flowableEvent);
        FlowableEntityEventImpl event = (FlowableEntityEventImpl) flowableEvent;
        ExecutionEntityImpl entity = ((ExecutionEntityImpl) event.getEntity());
        LOGGER.info("FlowCompletedListener:processInstanceId:{},businessKey {},processVariables{},variableInstances:{}", event.getProcessInstanceId(), entity.getBusinessKey(), entity.getProcessVariables(), entity.getVariableInstances());
        Object service = entity.getProcessVariables().get(Constant.FLOW_SERVICE);
        if (service != null){
            ProcessClient client = ApplicationContextUtils.getBean(service.toString(), ProcessClient.class);
            client.processCompleted(new IdStatusBo(entity.getBusinessKey(),entity.getVariableInstances().get(Constant.FLOW_STATUS).getTextValue()));
        }
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        //事务提交时触发
        return TransactionState.COMMITTING.name();
    }
}
